package com.qiantu.phone.ui.shotview;

import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.MODE;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.POWER;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.POWER_OFF;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.POWER_ON;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.TEMPERATURE;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.WIND_DIRECTION;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.WIND_SPEED;

import android.content.Context;
import android.util.Log;
import android.view.View;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControlDataAirConditionerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceModeValue;
import com.qiantu.api.entity.UniversalDeviceAction;
import com.qiantu.api.entity.UniversalDeviceData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.adapter.DeviceModeLabelAdapter;
import com.qiantu.phone.ui.adapter.DeviceModeValueAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.AirConditionerSeekBar;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class UniversalAirShotView extends BaseDeviceActView {
    private AirConditionerSeekBar airConditionerSeekBar;
    private RecyclerView modeRecyclerView;
    private RecyclerView modeValueRecyclerView;
    private DeviceModeLabelAdapter mDeviceModeLabelAdapter;
    private DeviceModeValueAdapter mDeviceModeValueAdapter;
    private String selectedLabel;
    private List<DeviceModeValue> powers;
    private List<DeviceModeValue> modes;
    private List<DeviceModeValue> speeds;
    private List<DeviceModeValue> directions;
    private UniversalDeviceData temperature;
    private String mode;
    private String windSpeed;
    private String windDirection;

    public UniversalAirShotView(Context context) {
        super(context);
    }

    @Override
    public int getLayoutId() {
        return R.layout.air_conditioner_shot_view;
    }

    public void setDevice(DeviceBean device){
        mDevice = device;
        this.type = device.getType();
        this.deviceType = device.getDeviceType();
        getData();
    }
    @Override
    public void initView() {
        airConditionerSeekBar = findViewById(R.id.air_conditioner_seek_bar);
        modeRecyclerView = findViewById(R.id.mode_recycler_view);
        modeValueRecyclerView = findViewById(R.id.mode_value_recycler_view);
        airConditionerSeekBar.setOnChangeListener(new AirConditionerSeekBar.OnChangeListener() {
            @Override
            public void onValueChanged(float value) {
            }

            @Override
            public void onStopTrackingTouch(float value) {
                addAct(POWER, POWER_ON);
                addAct(TEMPERATURE, getTempText(value));
            }

            @Override
            public void onSwitch(boolean isOpen) {
                if(isOpen){
                    addAct(POWER, POWER_ON);
                    addAct(TEMPERATURE, getTempText(airConditionerSeekBar.getTemp()));
                }else{
                    addAct(POWER, POWER_OFF);
                    removeAct(TEMPERATURE);
                }
                removeAct(MODE);
                removeAct(WIND_SPEED);
                removeAct(WIND_DIRECTION);
                mode = defaultValue;
                windSpeed =  defaultValue;
                windDirection =  defaultValue;
                setValueByLabel();
            }
        });
    }

    private void getData() {
        LLHttpManager.getDeviceTgpactions((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), new HttpCallback<HttpData<UniversalDeviceAction>>(null) {
            @Override
            public void onStart(Call call) {
                if (getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<UniversalDeviceAction> result) {
                rebuildData(result.getData().getTgpActions());
            }

            @Override
            public void onFail(Exception e) {
                if (getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if (getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void rebuildData(List<UniversalDeviceData> actionDtos) {
        powers = new ArrayList<>();
        modes = new ArrayList<>();
        speeds = new ArrayList<>();
        directions = new ArrayList<>();

        for (UniversalDeviceData actionDto : actionDtos) {
            if (!actionDto.getEnable()) {
                continue;
            }
            DeviceModeValue modeValue = new DeviceModeValue();
            modeValue.setName(actionDto.getRangeName());
            if (actionDto.getRangeIdentifier() != null) {
                int value = Integer.parseInt(actionDto.getRangeIdentifier());
                modeValue.setValue(value);
            } else {
                modeValue.setValue(0);
            }
            modeValue.setSort(actionDto.getSort());
            modeValue.setImage(actionDto.getDisplayImage());
            if (actionDto.getActionIdentifier().equals("mode")) {
                modes.add(modeValue);
            } else if (actionDto.getActionIdentifier().equals("windspeed")) {
                speeds.add(modeValue);
            } else if (actionDto.getActionIdentifier().equals("temperature")) {
                temperature = actionDto;
            } else if (actionDto.getActionIdentifier().equals("power")) {
                powers.add(modeValue);
            } else if (actionDto.getActionIdentifier().equals("winddirection")) {
                directions.add(modeValue);
            }
        }
        modes.sort(new Comparator<DeviceModeValue>() {
            @Override
            public int compare(DeviceModeValue o1, DeviceModeValue o2) {
                return o1.getSort() < o2.getSort() ? -1 : 1;
            }
        });
        speeds.sort(new Comparator<DeviceModeValue>() {
            @Override
            public int compare(DeviceModeValue o1, DeviceModeValue o2) {
                return o1.getSort() < o2.getSort() ? -1 : 1;
            }
        });
        directions.sort(new Comparator<DeviceModeValue>() {
            @Override
            public int compare(DeviceModeValue o1, DeviceModeValue o2) {
                return o1.getSort() < o2.getSort() ? -1 : 1;
            }
        });
        buildView();
    }

    private void buildView() {
        List<String> modeList = new ArrayList<>();
        airConditionerSeekBar.setMinMax(temperature.getMin(), temperature.getMax());
        if (modes.size() > 0) {
            modeList.add(getResources().getString(R.string.mode));
        }
        if (speeds.size() > 0) {
            modeList.add(getResources().getString(R.string.wind_speed));
        }
        if (directions.size() > 0) {
            modeList.add(getResources().getString(R.string.wind_direction));
        }
        if (modeList.size() == 0) {
            return;
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), modeList.size());
        modeRecyclerView.setLayoutManager(gridLayoutManager);
        mDeviceModeLabelAdapter = new DeviceModeLabelAdapter(getContext());
        mDeviceModeLabelAdapter.setData(modeList);
        mDeviceModeLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                selectedLabel = mDeviceModeLabelAdapter.getData().get(position);
                mDeviceModeLabelAdapter.selectItem(position);
                if (selectedLabel.equals(getResources().getString(R.string.mode))) {
                    mDeviceModeValueAdapter.setData(modes);
                    selectValue(true, mDevice.getMode());
                } else if (selectedLabel.equals(getResources().getString(R.string.wind_speed))) {
                    mDeviceModeValueAdapter.setData(speeds);
                    selectValue(false, mDevice.getWindSpeed());
                } else if (selectedLabel.equals(getResources().getString(R.string.wind_direction))) {
                    mDeviceModeValueAdapter.setData(directions);
                    selectValue(false, mDevice.getWindDirection());
                }
            }
        });
        modeRecyclerView.setAdapter(mDeviceModeLabelAdapter);
        mDeviceModeLabelAdapter.selectItem(0);
        selectedLabel = modeList.get(0);
        mDeviceModeValueAdapter = new DeviceModeValueAdapter(getContext());
        if (modes.size() != 0) {
            mDeviceModeValueAdapter.setData(modes);
        } else if (speeds.size() != 0) {
            mDeviceModeValueAdapter.setData(speeds);
        } else {
            mDeviceModeValueAdapter.setData(directions);
        }

        mDeviceModeValueAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                if (!airConditionerSeekBar.isOpen()) {
                    ToastUtils.show(R.string.device_off_disable);
                    return;
                }
                boolean isMode = false;
                DeviceModeValue valueBean = mDeviceModeValueAdapter.getData().get(position);
                if (selectedLabel.equals(getResources().getString(R.string.mode))) {
                    airConditionerSeekBar.setModeName(valueBean.getName());
                    mode = valueBean.getValue() + "";
                    isMode = true;
                    addAct(MODE, mode);
                } else if (selectedLabel.equals(getResources().getString(R.string.wind_speed))) {
                    windSpeed = valueBean.getValue() + "";
                    isMode = false;
                    addAct(WIND_SPEED, windSpeed);
                }else if (selectedLabel.equals(getResources().getString(R.string.wind_direction))) {
                    windDirection = valueBean.getValue() + "";
                    isMode = false;
                    addAct(WIND_DIRECTION, windDirection);
                }
                //切换模式需要更新颜色
                mDeviceModeValueAdapter.selectItem(isMode, position);
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        modeValueRecyclerView.setLayoutManager(linearLayoutManager);
        modeValueRecyclerView.setAdapter(mDeviceModeValueAdapter);
        updateView();
    }

    private String getTempText(float temp){
        String text = null;
        if (temp * 10 % 10 == 0) {
            text = (int) temp + "";
        } else {
            text = temp + "";
        }
        return text;
    }

    private void setValueByLabel() {
        if (selectedLabel.equals(getResources().getString(R.string.mode))) {
            setModeName();
            selectValue(true, mDevice.getMode());
        } else if (selectedLabel.equals(getResources().getString(R.string.wind_speed))) {
            selectValue(false, mDevice.getWindSpeed());
        }
    }

    private void selectValue(boolean isMode, Integer value) {
        //设备关闭不设置设置缓存里的模式
        if (!airConditionerSeekBar.isOpen()) {
            return;
        }
        for (int i = 0; i < mDeviceModeValueAdapter.getData().size(); i++) {
            if (mDeviceModeValueAdapter.getData().get(i).getValue() == value) {
                mDeviceModeValueAdapter.selectItem(isMode, i);
                break;
            }
        }
    }

    private void setStatusBySwitch(boolean isOpen) {
        if(mDeviceModeLabelAdapter == null)
            return;
        airConditionerSeekBar.setOpenState(isOpen);
        if (isOpen) {
            setValueByLabel();
        } else {
            mDeviceModeValueAdapter.clearSelected();
        }
    }

    private void setModeName() {
        if(modes == null)
            return;
        for (DeviceModeValue valueBean : modes) {
            if (mDevice.getMode().equals(valueBean.getValue())) {
                airConditionerSeekBar.setModeName(valueBean.getName());
                break;
            }
        }
    }
    @Override
    public void updateView() {
        if(mDeviceActMap.size() == 0){
            addAct(POWER, POWER_ON);
        }
        airConditionerSeekBar.setEnabled(true);
        airConditionerSeekBar.setTemp(Float.valueOf(mDevice.getTemperature()));
        setModeName();
        setStatusBySwitch(POWER_ON.equals(getState(POWER,  "0")));
    }
}
